package de.sendorian.app.forumArchive;

import java.io.File;
import java.io.FileFilter;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.hamcrest.Matcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import de.sendorian.app.forumArchive.domain.Forum;
import de.sendorian.app.forumArchive.domain.Topic;
import de.sendorian.util.io.RecursiveFileListIterator;


@Component
public class Collector {

    private @Value("#{config.downloadDir}") String downloadDir;

    private FileFilter filter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return StringUtils.endsWithIgnoreCase(pathname.getName(), ".png");
        }
    };


    public Set<String> collectImagesInForumDirs(List<Forum> forums, Matcher<Topic> topicMatcher) {
        Set<String> allDirs = new LinkedHashSet<String>();
        for (Forum forum : forums) {
            for (Topic topic : forum.getTopics()) {
                if (topicMatcher.matches(topic)) {
                    String topicDir = downloadDir + forum.getName() + File.separator + topic.getName();
                    allDirs.add(topicDir);
                }
            }
        }
        return collectImagesInFolders(allDirs);
    }


    public Set<String> collectImagesInFolders(Set<String> dirs) {
        Set<String> allFiles = new LinkedHashSet<String>();
        for (String sDir : dirs) {
            File dir = new File(sDir);
            if (dir.exists()) {
                Iterator<File> it = new RecursiveFileListIterator(dir, filter);
    
                while (it.hasNext()) {
                    allFiles.add(it.next().getAbsolutePath());
                }
            }
        }
        return allFiles;
    }

}
